import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

class FirebaseMessageService {
  static FirebaseMessageService? _instance;
  static FirebaseMessaging? _firebaseMessaging;

  // 单例模式
  static FirebaseMessageService get instance {
    _instance ??= FirebaseMessageService._internal();
    return _instance!;
  }

  FirebaseMessageService._internal();

  // 初始化Firebase Messaging
  Future<void> initialize() async {
    if (Firebase.apps.isEmpty) {
      await Firebase.initializeApp();
    }
    _firebaseMessaging = FirebaseMessaging.instance;
  }

  /// 请求Firebase消息通知权限
  ///
  /// 参数说明:
  /// * [alert] - 控制应用是否可以显示通知提醒
  /// * [announcement] - 控制通知是否可以被Siri朗读
  /// * [badge] - 控制应用是否可以更新应用图标角标数字
  /// * [carPlay] - 控制通知是否可以在CarPlay中显示（车载技术）
  /// * [criticalAlert] - 控制是否允许发送重要通知，这类通知可以绕过"勿扰模式"和静音设置
  /// * [provisional] - 控制是否请求临时授权，临时授权允许静默推送通知而不需要用户明确许可
  /// * [sound] - 控制应用是否可以为通知播放声音
  ///
  /// 返回NotificationSettings对象，包含用户授予的权限状态
  Future<NotificationSettings> requestPermission({
    bool alert = true,
    bool announcement = false,
    bool badge = true,
    bool carPlay = false,
    bool criticalAlert = false,
    bool provisional = false,
    bool sound = true,
  }) async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法.');
    }
    return await _firebaseMessaging!.requestPermission(
      alert: alert,
      announcement: announcement,
      badge: badge,
      carPlay: carPlay,
      criticalAlert: criticalAlert,
      provisional: provisional,
      sound: sound,
    );
  }

  // 获取FCM令牌
  Future<String?> getToken() async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法.');
    }
    return await _firebaseMessaging!.getToken();
  }

  // 监听令牌刷新
  Stream<String> get onTokenRefresh {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法.');
    }
    return _firebaseMessaging!.onTokenRefresh;
  }

  // 监听前台消息
  Stream<RemoteMessage> get onMessage {
    return FirebaseMessaging.onMessage;
  }

  // 监听应用从后台打开的消息
  Stream<RemoteMessage> get onMessageOpenedApp {
    return FirebaseMessaging.onMessageOpenedApp;
  }

  // 获取初始消息（应用从终止状态打开）
  Future<RemoteMessage?> getInitialMessage() async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    return await _firebaseMessaging!.getInitialMessage();
  }

  // 设置后台消息处理器
  static Future<void> setBackgroundMessageHandler(BackgroundMessageHandler handler) async {
    if (Firebase.apps.isEmpty) {
      await Firebase.initializeApp();
    }
    FirebaseMessaging.onBackgroundMessage(handler);
  }

  // 订阅主题
  Future<void> subscribeToTopic(String topic) async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    await _firebaseMessaging!.subscribeToTopic(topic);
  }

  // 取消订阅主题
  Future<void> unsubscribeFromTopic(String topic) async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    await _firebaseMessaging!.unsubscribeFromTopic(topic);
  }

  // 删除令牌
  Future<void> deleteToken() async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    await _firebaseMessaging!.deleteToken();
  }

  // 设置前台通知展示选项（仅iOS）
  Future<void> setForegroundNotificationPresentationOptions({
    bool alert = true,
    bool badge = true,
    bool sound = true,
  }) async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    await _firebaseMessaging!.setForegroundNotificationPresentationOptions(alert: alert, badge: badge, sound: sound);
  }

  // 获取通知设置
  Future<NotificationSettings> getNotificationSettings() async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    return await _firebaseMessaging!.getNotificationSettings();
  }

  // 设置自动初始化
  Future<void> setAutoInitEnabled(bool enabled) async {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    await _firebaseMessaging!.setAutoInitEnabled(enabled);
  }

  // 检查自动初始化状态
  bool isAutoInitEnabled() {
    if (_firebaseMessaging == null) {
      throw Exception('FirebaseMessageService 未初始化。请先调用 initialize() 方法..');
    }
    return _firebaseMessaging!.isAutoInitEnabled;
  }
}
